﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Commonlib;
namespace AlbonWeb.Manager.OrderManager
{
    public partial class Invoice : System.Web.UI.Page
    {
        protected readonly BLL.OrderBLL orderbll = new BLL.OrderBLL();
        protected readonly BLL.InvoiceBLL invoicebll = new BLL.InvoiceBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request["orderid"] != null)
                {
                    initData(Request["orderid"].ToString());
                }
            }
        }

        //加载invoice页数据
        protected void initData(string orderid)
        {
            
            DataTable dtOrder = orderbll.getOrderByID(orderid);
            invoiceNo.Text = dtOrder.Rows[0]["invoiceNo"].ToString();
            if (invoiceNo.Text != "")
            {
                BLL.InvoiceBLL invoicebll = new BLL.InvoiceBLL();
                DataTable dtInvoice = invoicebll.getInvoiceByNo(invoiceNo.Text);
                if (dtInvoice.Rows.Count > 0)
                {
                    //如果Invoice已经计算，则显示保存的静态页
                    //if (decimal.Parse(dtInvoice.Rows[0]["totalMoney"].ToString()) > 0)
                    //{
                    //    Response.Redirect(dtInvoice.Rows[0]["invoicePath"].ToString());
                    //}
                    //页头
                    payMethod.Text = dtInvoice.Rows[0]["payMethod"].ToString();
                    for (int i = 0; i < ddlpayMethod.Items.Count; i++)
                    {
                        if (ddlpayMethod.Items[i].Text == payMethod.Text)
                        {
                            ddlpayMethod.SelectedIndex = i;
                        }
                    }
                    if (dtInvoice.Rows[0]["totalDate"].ToString() != "")
                    {
                        totalDate.Text = DateTime.Parse(dtInvoice.Rows[0]["totalDate"].ToString()).ToString("yyyy/MM/dd hh:mm:ss");
                    }
                    refNo.Text = dtOrder.Rows[0]["refNo"].ToString();
                    userName.Text = dtOrder.Rows[0]["userName"].ToString();
                    shipMethod.Text = dtOrder.Rows[0]["shipMethod"].ToString();

                    //PayMethod
                    string cmdstr = "select * from PayMethod";
                    SqlHelper.BindDropDownList(ddlpayMethod, "methodName", "percentage", SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null);

                    //Cloth Charge
                    bindClothCharge(orderid);
                    //Item Charge(CMT Charge)
                    bindItemCharge(orderid);
                    //Style Charge
                    bindStyleCharge(orderid);
                    //Shipping Charge
                    bindShipCharge(orderid);
                    //ExtraCharge
                    bindExtraCharge();
                    //OverSize Charge
                    bindOverSizeCharge(orderid);
                }
            }

        }

        
        //订单布料的价格列表 
        private void bindClothCharge(string orderid)
        {
            float totalCharge=0;
            DataTable dt = invoicebll.clothCharge(orderid);
            bindRep(dt, repCloth);
            foreach (DataRow dr in dt.Rows)
            {
                totalCharge += float.Parse(dr["total"].ToString());
            }
            clothMoney.Text = totalCharge.ToString("0.00");

        }
        //订单项手工费列表(没有分CMT和Landed两种方式)
        private void bindItemCharge(string orderid)
        {
            float totalCharge = 0;
            DataTable dt = invoicebll.itemCharge(orderid);
            bindRep(dt, repItem);
            foreach (DataRow dr in dt.Rows)
            {
                totalCharge += float.Parse(dr["total"].ToString());       
            }
            itemMoney.Text = totalCharge.ToString("0.00");
        }
        //订单项的样式价格列表
        private void bindStyleCharge(string orderid)
        {
            float totalCharge = 0;
            BLL.OrderItemBLL orderitembll = new BLL.OrderItemBLL();
            DataTable dtItem = orderitembll.getItemByOrderID(orderid);
            dlItem.DataSource = dtItem;
            dlItem.DataBind();
            foreach (DataListItem dli in dlItem.Items)
            {
                if (dli.ItemIndex != -1)
                {
                    int qty = int.Parse(((Label)dli.FindControl("Qty")).Text); 
                    float total = 0;
                    string orderitemid = ((HiddenField)dli.FindControl("hforderitemid")).Value;
                    Repeater repStyle = (Repeater)dli.FindControl("repStyle");
                    BLL.StylePriceBLL stylepricebll = new BLL.StylePriceBLL();
                    DataTable dtStylePrice=stylepricebll.getItemStylePrice(orderitemid);
                    if (dtStylePrice.Rows.Count > 0)
                    {
                       
                        foreach (DataRow dr in dtStylePrice.Rows)
                        {
                            total += float.Parse(dr["stylePrice"].ToString());
                        }
                        bindRep(dtStylePrice, repStyle);
                    }
                    else
                    {
                        dli.CssClass = "NoPrint";
                    }
                    totalCharge += qty * total;
                }
            }
            styleMoney.Text = totalCharge.ToString("0.00");
        }
        //超出尺寸收费
        private void bindOverSizeCharge(string orderid)
        {
            float totalCharge = 0;
            DataTable dt = invoicebll.overSizeCharge(orderid);
            bindRep(dt, repOverSize);
            foreach (DataRow dr in dt.Rows)
            {
                totalCharge += float.Parse(dr["total"].ToString());
            }
            overSizeMoney.Text = totalCharge.ToString("0.00");
        }
        //运费
        private void bindShipCharge(string orderid)
        {
            //系统中的价钱以 500g/斤 为单位？
            float totalCharge = 0;
            DataTable dt = invoicebll.shipCharge(orderid);
            bindRep(dt, repShip);
            int fitNum = 0;
            float totalweight = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if(bool.Parse(dr["FT"].ToString()))
                {
                    fitNum++;
                }
                totalweight += float.Parse(dr["total"].ToString());
            }
            totalCharge = invoicebll.getTotalShipCharge(orderid,fitNum,totalweight);
            shipMoney.Text = totalCharge.ToString("0.00");
        }
        //绑定附加收费
        private void bindExtraCharge()
        {
            float totalCharge = 0;
            DataTable dt=invoicebll.getExtras(invoiceNo.Text);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                totalCharge += float.Parse(dt.Rows[i]["extraCharge"].ToString());
            }
            bindRep(dt,repExtra);
            extraMoney.Text = totalCharge.ToString("0.00");
        }

        //绑定Repeater，如果数据源没有数据行，则不进行绑定
        private void bindRep(DataTable dt, Repeater rep)
        {
            if (dt.Rows.Count > 0)
            {
                rep.DataSource = dt;
                rep.DataBind();
            }
        }
        //汇总数据（JS实现），保存静态页
        protected void Total_Click(object sender, EventArgs e)
        {
            Albon.Model.Invoice invoice = new Albon.Model.Invoice();
            invoice.invoiceNo =int.Parse(invoiceNo.Text);
            invoice.invoicePath = "/StaticPage/Invoice/" + userName.Text + "/" + invoiceNo.Text + ".html";
            invoice.payMethod = ddlpayMethod.SelectedItem.Text;
            invoice.invoiceTotal = decimal.Parse(hftotal.Value);
            invoice.totalMoney =decimal.Parse(string.Format("{0:0.00}", invoice.invoiceTotal *(1+decimal.Parse(ddlpayMethod.SelectedValue))));
            invoice.adder = User.Identity.Name;
            //先保存数据
            if (invoicebll.totalMoney(invoice))
            {
                //再保存静态页
               invoicebll.saveAsStaticFile(Request.Url.ToString(), userName.Text, invoiceNo.Text);
            }
        }

        //增加额外收费
        protected void addExtras_Click(object sender, EventArgs e)
        {
            Albon.Model.ExtraCharge extra = new Albon.Model.ExtraCharge();
            extra.invoiceNo =int.Parse(invoiceNo.Text);
            extra.extraCharge = decimal.Parse(Extra.Text.Trim());
            extra.remark = Remark.Text.Trim();
            invoicebll.addExtraCharge(extra);
            bindExtraCharge();
        }
        //删除额外收费信息
        protected void imgDelete_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton imgDelete=(ImageButton)sender;
            invoicebll.removeExtraCharge(imgDelete.CommandName );
            bindExtraCharge();
        }
    }
}